import json
import os
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Any

try:
    import wxauto
    # 直接使用真实的wxauto库
except ImportError:
    # 如果无法导入wxauto，创建模拟实现
    class WXAutoMock:
        """模拟微信API的类"""
        
        def __init__(self):
            """初始化模拟对象"""
            self.sessions = ["文件传输助手", "测试用户1", "测试用户2", "测试群1"]
            self.current_session = None
            
        def GetSessionList(self):
            """获取会话列表"""
            return self.sessions
        
        def ChatWith(self, who):
            """切换会话"""
            if who in self.sessions:
                self.current_session = who
                return True
            return False
        
        def GetAllMessage(self):
            """获取所有消息"""
            mock_messages = [
                "测试用户1:[2023/01/01 10:00:00]你好",
                "我:[2023/01/01 10:01:00]你好，很高兴认识你",
                "测试用户1:[2023/01/01 10:02:00]最近在忙什么？",
                "我:[2023/01/01 10:03:00]在开发一个微信聊天助手"
            ]
            return "\n".join(mock_messages)
        
        def SendMsg(self, msg):
            """发送消息"""
            return True

    # 创建模拟微信API类
    class WeChat(WXAutoMock):
        """模拟wxauto.WeChat类"""
        pass
        
    # 设置模拟的wxauto模块
    class WXAutoModuleMock:
        def __init__(self):
            self.WeChat = WeChat
            
    # 创建模拟微信API实例
    wxauto = WXAutoModuleMock()

from app.core.config import settings
from app.core.logging import logger
from app.models.messages import MessageDirection, MessageStatus, MessageType

from app.services.speech.speech_to_text import SpeechToTextService

class WXAutoService:
    """微信自动化服务，使用wxauto库通过UI自动化获取微信数据"""
    
    def __init__(self):
        """初始化微信自动化服务"""
        logger.info("Initializing WXAuto Service")
        self.wx_module = wxauto
        self.wx = None
        self.data_dir = settings.WECHAT_DATA_DIR
        
        # 确保数据目录存在
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
            
        # 尝试初始化微信实例
        self._init_wechat_instance()
        
    def _init_wechat_instance(self):
        """初始化微信实例"""
        try:
            if hasattr(self.wx_module, 'WeChat'):
                logger.info("使用 wxauto.WeChat() 初始化微信实例")
                self.wx = self.wx_module.WeChat()
                return True
            else:
                logger.error("wxauto模块中没有WeChat类")
                return False
        except Exception as e:
            logger.error(f"初始化微信实例失败: {str(e)}")
            return False
    
    def check_login(self) -> bool:
        """
        检查微信是否已登录
        
        Returns:
            bool: 是否已登录
        """
        try:
            # 首先确保实例已初始化
            if self.wx is None:
                if not self._init_wechat_instance():
                    return False
                    
            # 尝试获取会话列表，如果能获取则认为已登录
            sessions = self.get_session_list()
            return len(sessions) > 0
        except Exception as e:
            logger.error(f"检查微信登录状态失败: {str(e)}")
            return False
    
    def get_session_list(self) -> List[str]:
        """
        获取会话列表
        
        Returns:
            List[str]: 会话名称列表
        """
        try:
            # 首先确保实例已初始化
            if self.wx is None:
                if not self._init_wechat_instance():
                    return []
                    
            # 从WeChat实例获取会话列表
            if hasattr(self.wx, 'GetSessionList'):
                sessions = self.wx.GetSessionList()
                
                # 处理wxauto返回的会话列表
                if sessions:
                    try:
                        # 字典类型的会话列表
                        if isinstance(sessions, dict):
                            result = []
                            for session_name in sessions:
                                if session_name:  # 确保会话名不为空
                                    result.append(str(session_name))
                            return result
                        
                        # 可迭代类型的会话列表
                        elif hasattr(sessions, '__iter__'):
                            result = []
                            for session in sessions:
                                if session:  # 确保会话名不为空
                                    result.append(str(session))
                            return result
                        
                        # 单个字符串
                        elif isinstance(sessions, str):
                            return [sessions]
                        
                        # 无法识别的类型
                        else:
                            logger.warning(f"无法识别的会话列表类型: {type(sessions)}")
                            return [str(sessions)]
                    except Exception as e:
                        logger.error(f"处理会话列表失败: {str(e)}")
                        return []
                else:
                    return []
            else:
                logger.error("微信实例没有提供GetSessionList方法")
                return []
        except Exception as e:
            logger.error(f"获取会话列表失败: {str(e)}")
            return []
    
    def chat_with(self, session_name: str) -> bool:
        """
        切换到指定会话
        
        Args:
            session_name: 会话名称
            
        Returns:
            bool: 是否成功切换
        """
        try:
            # 首先确保实例已初始化
            if self.wx is None:
                if not self._init_wechat_instance():
                    return False
                    
            # 从WeChat实例切换会话
            if hasattr(self.wx, 'ChatWith'):
                return self.wx.ChatWith(session_name)
            else:
                logger.error("微信实例没有提供ChatWith方法")
                return False
        except Exception as e:
            logger.error(f"切换到会话 {session_name} 失败: {str(e)}")
            return False
    
    def get_message_list(self) -> List[Dict[str, Any]]:
        """
        获取当前会话的消息列表
        
        Returns:
            List[Dict[str, Any]]: 消息记录列表
        """
        try:
            # 首先确保实例已初始化
            if self.wx is None:
                logger.error("微信实例未初始化")
                if not self._init_wechat_instance():
                    return []
            
            # 从WeChat实例获取所有消息
            if hasattr(self.wx, 'GetAllMessage'):
                try:
                    # 调用GetAllMessage获取消息
                    logger.info("正在从微信获取消息...")
                    raw_messages = self.wx.GetAllMessage()
                    
                    # 记录原始消息类型和内容
                    logger.debug(f"原始消息类型: {type(raw_messages)}")
                    logger.debug(f"原始消息内容: {raw_messages}")
                    
                    # 判断消息是否为空
                    if raw_messages is None:
                        logger.warning("获取到的消息为空")
                        return []
                    
                    # 如果是字符串，尝试解析
                    if isinstance(raw_messages, str):
                        # 检查空字符串
                        if not raw_messages.strip():
                            logger.warning("获取到的消息字符串为空")
                            return []
                        messages = raw_messages.split('\n')
                        logger.info(f"将字符串消息拆分为 {len(messages)} 条记录")
                    # 如果是列表，直接使用
                    elif isinstance(raw_messages, list):
                        # 检查空列表
                        if not raw_messages:
                            logger.warning("获取到的消息列表为空")
                            return []
                        messages = raw_messages
                        logger.info(f"获取到 {len(messages)} 条列表消息")
                    else:
                        # 尝试转换为字符串后解析
                        try:
                            str_messages = str(raw_messages)
                            # 检查转换后的字符串是否为空
                            if not str_messages.strip():
                                logger.warning("转换后的消息字符串为空")
                                return []
                            messages = str_messages.split('\n')
                            logger.info(f"将其他类型消息转换为字符串并拆分为 {len(messages)} 条记录")
                        except Exception as e:
                            logger.error(f"无法转换消息格式: {str(e)}")
                            return []
                    
                    # 过滤空消息
                    messages = [msg for msg in messages if msg and (not isinstance(msg, str) or msg.strip())]
                    
                    # 解析消息列表
                    parsed_messages = []
                    for i, msg in enumerate(messages):
                        try:
                            # 记录当前处理的消息
                            logger.debug(f"正在处理第 {i+1} 条消息: {msg}")
                            
                            # 如果已经是字典格式，验证必要字段
                            if isinstance(msg, dict):
                                parsed_msg = self._validate_message_dict(msg)
                            else:
                                # 如果是字符串，尝试解析
                                parsed_msg = self._parse_message_text(msg, "")
                            
                            if parsed_msg:
                                parsed_messages.append(parsed_msg)
                                logger.debug(f"消息 {i+1} 解析成功")
                            
                        except Exception as e:
                            logger.error(f"处理第 {i+1} 条消息时出错: {str(e)}")
                            continue
                    
                    logger.info(f"成功解析 {len(parsed_messages)} 条消息")
                    return parsed_messages
                    
                except Exception as e:
                    logger.error(f"获取和解析消息失败: {str(e)}")
                    return []
            else:
                logger.error("微信实例没有提供GetAllMessage方法")
                return []
        except Exception as e:
            logger.error(f"获取消息列表失败: {str(e)}")
            return []
    
    def get_messages(self, session_name: str) -> List[Dict[str, Any]]:
        """
        获取指定会话的消息记录
        
        Args:
            session_name: 会话名称
            
        Returns:
            List[Dict[str, Any]]: 消息记录列表
        """
        try:
            # 切换到指定会话
            if not self.chat_with(session_name):
                logger.error(f"无法切换到会话 {session_name}")
                return []
            
            # 获取所有消息
            return self.get_message_list()
        except Exception as e:
            logger.error(f"获取会话 {session_name} 的消息记录失败: {str(e)}")
            return []
    
    def send_message(self, content: str) -> bool:
        """
        在当前会话中发送消息
        
        Args:
            content: 消息内容
            
        Returns:
            bool: 是否成功发送
        """
        try:
            # 首先确保实例已初始化
            if self.wx is None:
                if not self._init_wechat_instance():
                    return False
                    
            # 从WeChat实例发送消息
            if hasattr(self.wx, 'SendMsg'):
                return self.wx.SendMsg(content)
            else:
                logger.error("微信实例没有提供SendMsg方法")
                return False
        except Exception as e:
            logger.error(f"发送消息失败: {str(e)}")
            return False
    
    def _parse_messages(self, messages_text: str, session_name: str) -> List[Dict[str, Any]]:
        """
        解析消息文本
        
        Args:
            messages_text: 消息文本
            session_name: 会话名称
            
        Returns:
            List[Dict[str, Any]]: 解析后的消息列表
        """
        if not messages_text:
            return []
        
        result = []
        lines = messages_text.split('\n')
        
        for line in lines:
            try:
                # 消息格式: "发送者:[日期 时间]消息内容"
                if ":[" not in line or "]" not in line:
                    continue
                
                sender, rest = line.split(":[", 1)
                datetime_str, content = rest.split("]", 1)
                
                # 格式化日期时间
                try:
                    sent_at = datetime.strptime(datetime_str, "%Y/%m/%d %H:%M:%S")
                except ValueError:
                    # 尝试其他可能的日期格式
                    try:
                        sent_at = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
                    except ValueError:
                        sent_at = datetime.now()
                
                # 确定消息方向（收/发）
                direction = MessageDirection.OUTGOING if sender == "我" else MessageDirection.INCOMING
                
                # 确定消息类型（暂时只处理文本）
                msg_type = MessageType.TEXT
                
                # 创建消息对象
                message = {
                    "session_name": session_name,
                    "sender": sender,
                    "content": content,
                    "sent_at": sent_at,
                    "direction": direction,
                    "msg_type": msg_type,
                    "status": MessageStatus.SENT
                }
                
                result.append(message)
            except Exception as e:
                logger.error(f"解析消息失败: {line} - {str(e)}")
        
        return result
    
    def _save_to_cache(self, session_name: str, messages: List[Dict[str, Any]]) -> None:
        """
        保存消息到本地缓存
        
        Args:
            session_name: 会话名称
            messages: 消息列表
        """
        try:
            # 创建会话目录
            session_dir = os.path.join(self.data_dir, self._sanitize_filename(session_name))
            if not os.path.exists(session_dir):
                os.makedirs(session_dir)
            
            # 缓存文件路径
            cache_file = os.path.join(session_dir, "messages.json")
            
            # 读取现有缓存
            existing_messages = []
            if os.path.exists(cache_file):
                try:
                    with open(cache_file, 'r', encoding='utf-8') as f:
                        existing_messages = json.load(f)
                except Exception as e:
                    logger.error(f"读取缓存文件失败: {str(e)}")
            
            # 转换日期时间为字符串
            serializable_messages = []
            for msg in messages:
                msg_copy = msg.copy()
                if isinstance(msg_copy["sent_at"], datetime):
                    msg_copy["sent_at"] = msg_copy["sent_at"].strftime("%Y-%m-%d %H:%M:%S")
                serializable_messages.append(msg_copy)
            
            # 合并消息（去重）
            merged_messages = self._merge_messages(existing_messages, serializable_messages)
            
            # 保存到文件
            with open(cache_file, 'w', encoding='utf-8') as f:
                json.dump(merged_messages, f, ensure_ascii=False, indent=2)
            
            logger.info(f"已保存 {len(merged_messages)} 条消息到缓存: {cache_file}")
        except Exception as e:
            logger.error(f"保存消息到缓存失败: {str(e)}")
    
    def _merge_messages(self, existing: List[Dict[str, Any]], new: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        合并消息，去除重复
        
        Args:
            existing: 现有消息列表
            new: 新消息列表
            
        Returns:
            List[Dict[str, Any]]: 合并后的消息列表
        """
        # 将消息转换为集合，以便去重
        existing_set = {self._message_to_key(msg): msg for msg in existing}
        new_set = {self._message_to_key(msg): msg for msg in new}
        
        # 合并两个集合
        merged = {**existing_set, **new_set}
        
        # 按时间排序
        sorted_messages = sorted(
            merged.values(), 
            key=lambda x: datetime.strptime(x["sent_at"], "%Y-%m-%d %H:%M:%S") 
                if isinstance(x["sent_at"], str) 
                else x["sent_at"]
        )
        
        return sorted_messages
    
    def _message_to_key(self, msg: Dict[str, Any]) -> str:
        """
        将消息转换为唯一键
        
        Args:
            msg: 消息对象
            
        Returns:
            str: 唯一键
        """
        # 使用发送者、时间和内容前20个字符作为唯一键
        sent_at = msg["sent_at"]
        if isinstance(sent_at, datetime):
            sent_at = sent_at.strftime("%Y-%m-%d %H:%M:%S")
        
        key = f"{msg['sender']}:{sent_at}:{msg['content'][:20]}"
        return key
    
    def _sanitize_filename(self, filename: str) -> str:
        """
        清理文件名，移除不允许的字符
        
        Args:
            filename: 原始文件名
            
        Returns:
            str: 清理后的文件名
        """
        # 替换不允许的字符
        invalid_chars = '<>:"/\\|?*'
        for char in invalid_chars:
            filename = filename.replace(char, '_')
        
        return filename

    def _parse_message_text(self, message_text: str, session_name: str) -> Dict[str, Any]:
        """
        解析单条消息文本
        
        Args:
            message_text: 单条消息文本
            session_name: 会话名称
            
        Returns:
            Dict[str, Any]: 解析后的消息
        """
        try:
            # 如果不是字符串类型，尝试转换为标准消息对象
            if not isinstance(message_text, str):
                logger.debug(f"收到非字符串消息: {type(message_text)}")
                return self._convert_wxauto_message(message_text)
                
            logger.debug(f"开始解析消息文本: {message_text}")
            
            # 如果消息文本为空，返回空字典
            if not message_text or not message_text.strip():
                logger.warning("消息文本为空")
                return {}
            
            # 消息格式: "发送者:[日期 时间]消息内容"
            if ":[" not in message_text or "]" not in message_text:
                # 如果不符合标准格式，尝试作为纯文本消息处理
                logger.debug("消息不符合标准格式，作为纯文本处理")
                return {
                    "direction": MessageDirection.INCOMING,
                    "msg_type": MessageType.TEXT,
                    "content": message_text.strip(),
                    "sent_at": datetime.now(),
                    "status": MessageStatus.RECEIVED,
                    "extra_data": {"raw_text": True}
                }
            
            # 解析发送者和消息内容
            try:
                sender, rest = message_text.split(":[", 1)
                datetime_str, content = rest.split("]", 1)
                
                logger.debug(f"解析结果 - 发送者: {sender}, 时间: {datetime_str}, 内容: {content}")
                
                # 格式化日期时间
                message_time = self._parse_message_time(datetime_str)
                
                # 确定消息方向
                direction = MessageDirection.OUTGOING if sender.strip() == "我" else MessageDirection.INCOMING
                
                # 确定消息类型
                msg_type = self._determine_message_type_from_content(content)
                
                # 创建消息字典
                message = {
                    "direction": direction,
                    "msg_type": msg_type,
                    "content": content.strip(),
                    "sent_at": message_time,
                    "status": MessageStatus.RECEIVED if direction == MessageDirection.INCOMING else MessageStatus.SENT,
                    "extra_data": {
                        "sender": sender.strip(),
                        "session_name": session_name,
                        "parsed": True
                    }
                }
                
                logger.debug(f"消息解析成功: {message}")
                return message
                
            except ValueError as e:
                logger.warning(f"解析消息格式失败: {str(e)}")
                # 返回一个基本的消息对象
                return {
                    "direction": MessageDirection.INCOMING,
                    "msg_type": MessageType.TEXT,
                    "content": message_text.strip(),
                    "sent_at": datetime.now(),
                    "status": MessageStatus.RECEIVED,
                    "extra_data": {"parse_error": str(e)}
                }
                
        except Exception as e:
            logger.error(f"解析消息文本失败: {str(e)}")
            # 返回一个错误状态的消息对象
            return {
                "direction": MessageDirection.INCOMING,
                "msg_type": MessageType.TEXT,
                "content": message_text.strip(),
                "sent_at": datetime.now(),
                "status": MessageStatus.ERROR,
                "extra_data": {"error": str(e)}
            }
            
    def _determine_message_type_from_content(self, content: str) -> str:
        """
        根据消息内容确定消息类型
        
        Args:
            content: 消息内容
            
        Returns:
            str: 消息类型
        """
        content = content.strip()
        
        # 检查特殊标记
        if "[图片]" in content:
            return MessageType.IMAGE
        elif "[语音]" in content:
            return MessageType.VOICE
        elif "[视频]" in content:
            return MessageType.VIDEO
        elif "[文件]" in content:
            return MessageType.FILE
        elif "[链接]" in content:
            return MessageType.LINK
        elif "[位置]" in content:
            return MessageType.LOCATION
        elif "[系统消息]" in content:
            return MessageType.SYSTEM
        
        # 默认为文本类型
        return MessageType.TEXT

    def _parse_message_time(self, time_str: str) -> datetime:
        """
        解析消息时间
        
        Args:
            time_str: 时间字符串
            
        Returns:
            datetime: 解析后的时间对象
        """
        try:
            # 尝试不同的时间格式
            formats = [
                "%Y/%m/%d %H:%M:%S",
                "%Y-%m-%d %H:%M:%S",
                "%m/%d/%Y %H:%M:%S",
                "%Y年%m月%d日 %H:%M:%S"
            ]
            
            for fmt in formats:
                try:
                    return datetime.strptime(time_str, fmt)
                except ValueError:
                    continue
                
            # 如果所有格式都失败，返回当前时间
            logger.warning(f"无法解析时间格式: {time_str}")
            return datetime.now()
            
        except Exception as e:
            logger.error(f"解析消息时间失败: {str(e)}")
            return datetime.now()

    def _save_media_content(self, msg_type: str, content: str, session_name: str, extra_data: Dict = None) -> Dict:
        """
        保存媒体内容到本地目录
        
        Args:
            msg_type: 消息类型
            content: 消息内容
            session_name: 会话名称(用于创建目录)
            extra_data: 额外数据
            
        Returns:
            Dict: 包含媒体文件元数据的字典
        """
        if not extra_data:
            extra_data = {}
            
        # 如果消息类型不是媒体类型，直接返回原始extra_data
        if msg_type not in [MessageType.IMAGE, MessageType.FILE, MessageType.VOICE, MessageType.VIDEO]:
            return extra_data
            
        try:
            # 创建存储目录
            media_type_dir = {
                MessageType.IMAGE: "images",
                MessageType.FILE: "files",
                MessageType.VOICE: "voices",
                MessageType.VIDEO: "videos"
            }.get(msg_type, "others")
            
            # 使用会话名称创建唯一目录
            safe_session_name = re.sub(r'[\\/:*?"<>|]', '_', session_name)
            media_dir = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
                "data", "media", media_type_dir, safe_session_name
            )
            
            # 确保目录存在
            os.makedirs(media_dir, exist_ok=True)
            
            # 尝试获取媒体文件路径或数据
            media_path = None
            file_name = None
            
            # 如果extra_data中已经包含媒体文件路径或数据
            if extra_data.get("media_url"):
                media_path = extra_data["media_url"]
                file_name = os.path.basename(media_path)
            elif extra_data.get("raw_data"):
                # 处理原始数据
                pass  # 需要根据实际情况处理
                
            # 如果没有找到媒体路径，尝试从消息内容中解析
            if not media_path and "[" in content and "]" in content:
                # 尝试解析描述中可能包含的媒体信息
                pass  # 需要根据实际情况处理
                
            # 如果找到了媒体路径，复制到目标目录
            if media_path and os.path.exists(media_path):
                # 生成目标文件名（使用原始文件名或生成新名称）
                if not file_name:
                    file_ext = os.path.splitext(media_path)[1]
                    file_name = f"{int(time.time())}_{random.randint(1000, 9999)}{file_ext}"
                    
                target_path = os.path.join(media_dir, file_name)
                
                # 复制文件
                if not os.path.exists(target_path):
                    shutil.copy2(media_path, target_path)
                    
                # 更新元数据
                extra_data["media_local_path"] = target_path
                extra_data["media_filename"] = file_name
                extra_data["media_size"] = os.path.getsize(target_path)
                extra_data["media_available"] = True
                
                # 语音消息特殊处理：进行语音转文字
                if msg_type == MessageType.VOICE:
                    speech_to_text = SpeechToTextService()
                    success, text_result = speech_to_text.convert_voice_to_text(target_path)
                    
                    # 保存转换结果
                    extra_data["speech_to_text_success"] = success
                    if success:
                        extra_data["speech_to_text"] = text_result
                        # 如果原始content没有实质内容（只有[语音]标识），则用转换后的文字替代
                        if content.strip() == "[语音]":
                            content = f"[语音] {text_result}"
                    else:
                        extra_data["speech_to_text_error"] = text_result
                
            return extra_data
            
        except Exception as e:
            logger.error(f"保存媒体内容失败: {str(e)}")
            extra_data["media_error"] = str(e)
            return extra_data

    def _convert_wxauto_message(self, msg: Dict, session_name: str = "") -> Dict:
        """
        转换wxauto获取的消息格式
        
        Args:
            msg: wxauto格式的消息
            session_name: 会话名称
            
        Returns:
            Dict: 标准格式的消息
        """
        # 基本的消息数据
        # ... existing code ...
        
        # 确定消息类型
        msg_type = self._determine_message_type(msg)
        
        # 获取消息内容
        content = msg.get("content", "")
        
        # 处理额外数据
        extra_data = msg.get("extra_data", {})
        
        # 处理媒体文件
        if msg_type in [MessageType.IMAGE, MessageType.FILE, MessageType.VOICE, MessageType.VIDEO]:
            extra_data = self._save_media_content(msg_type, content, session_name, extra_data)
            
            # 如果是语音消息且成功转换为文字，更新content
            if msg_type == MessageType.VOICE and extra_data.get("speech_to_text_success") and extra_data.get("speech_to_text"):
                content = f"[语音] {extra_data['speech_to_text']}"
        
        # 返回标准格式的消息
        return {
            "session_id": None,  # 由调用方设置
            "contact_id": None,  # 由调用方设置
            "msg_type": msg_type,
            "content": content,
            "direction": msg_direction,
            "sent_at": msg_time,
            "status": MessageStatus.RECEIVED if msg_direction == MessageDirection.INCOMING else MessageStatus.SENT,
            "extra_data": extra_data
        }

    def _determine_message_type(self, msg: Any) -> str:
        """
        确定消息类型
        
        Args:
            msg: wxauto消息对象
            
        Returns:
            str: 消息类型
        """
        try:
            # 检查消息属性来确定类型
            if hasattr(msg, "type"):
                msg_type = str(msg.type).lower()
                if msg_type in ["text", "image", "voice", "video", "file", "link", "location"]:
                    return msg_type
            
            # 检查消息内容特征
            content = str(msg)
            if "[图片]" in content:
                return MessageType.IMAGE
            elif "[语音]" in content:
                return MessageType.VOICE
            elif "[视频]" in content:
                return MessageType.VIDEO
            elif "[文件]" in content:
                return MessageType.FILE
            elif "[链接]" in content:
                return MessageType.LINK
            elif "[位置]" in content:
                return MessageType.LOCATION
            
            # 默认为文本类型
            return MessageType.TEXT
            
        except Exception as e:
            logger.error(f"确定消息类型失败: {str(e)}")
            return MessageType.OTHER

    def _extract_message_content(self, msg: Any) -> str:
        """
        提取消息内容
        
        Args:
            msg: wxauto消息对象
            
        Returns:
            str: 消息内容
        """
        try:
            # 首先尝试获取text属性
            if hasattr(msg, "text"):
                return str(msg.text)
            
            # 然后尝试获取content属性
            if hasattr(msg, "content"):
                return str(msg.content)
            
            # 最后尝试直接转换为字符串
            return str(msg)
            
        except Exception as e:
            logger.error(f"提取消息内容失败: {str(e)}")
            return ""

    def _validate_message_dict(self, msg: Dict[str, Any]) -> Dict[str, Any]:
        """
        验证并补充消息字典的必要字段
        
        Args:
            msg: 消息字典
            
        Returns:
            Dict[str, Any]: 验证并补充后的消息字典
        """
        required_fields = {
            "direction": MessageDirection.INCOMING,
            "msg_type": MessageType.TEXT,
            "content": "",
            "sent_at": datetime.now(),
            "status": MessageStatus.RECEIVED
        }
        
        # 补充缺失字段
        for field, default_value in required_fields.items():
            if field not in msg or msg[field] is None:
                msg[field] = default_value
                
        return msg